package cn.itcast.netty.c2;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import lombok.val;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * 需求：channel关闭后，能处理逻辑
 */
@Slf4j
public class CloseFutureClient {

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler());
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080));

        Channel channel = channelFuture.sync().channel();

        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            while (true){
                String next = scanner.next();
                if ("q".equals(next)){
                    channel.close(); //此方法也是一个异步非阻塞的方法
                    break;
                } 
                channel.writeAndFlush(next);
            }
        },"input").start();

        /*ChannelFuture closeFuture = channel.closeFuture();
        log.debug("close waiting...");
        closeFuture.sync(); //main 线程在此阻塞
        log.debug("处理关闭之后的事情");*/

        //第2种写法
        ChannelFuture closeFuture = channel.closeFuture();
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.debug("处理关闭之后的事情");
                group.shutdownGracefully();//优雅的关闭EventLoopGroup线程
            }
        });


    }
}
